<?php

/**
 * This is the model class for table "{{admin}}".
 *
 * The followings are the available columns in table '{{admin}}':
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $salt
 * @property string $email
 * @property string $profile
 * @property string $action_string
 */
class Admin extends MyARContent
{

    public $tableName = 'admin';
    public $new_pass; // Mật khẩu mới
    public $re_new_pass; // Mật khẩu mới
    public $old_pass; // Mật khẩu cũ

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Admin the static model class
     */

    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{admin}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('username', 'required'),
            array('username, password, new_pass, salt, email', 'length', 'max' => 128),
            array('email', 'email'),
            array('profile, action_string', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, username, password, salt, email, profile, action_string', 'safe', 'on' => 'search'),
            array('profile, action_string', 'safe'),
            array('new_pass', 'required', 'on' => 'create'),
            array('new_pass, old_pass', 'required', 'on' => 'changePassword'),
            array('old_pass', 'checkOldPassword', 'on' => 'changePassword'),
            //Xác nhận email để gửi link lấy lại mật khẩu
            array('email', 'required', 'on' => 'forgotPassword'),
            //Đặt lại mật khẩu
            array('new_pass, re_new_pass', 'required', 'on' => 'setNewPassword'),
            array('re_new_pass', 'compare', 'compareAttribute' => 'new_pass', 'on' => 'setNewPassword'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        $relate = parent::relations();
        $relate['posts'] = array(self::HAS_MANY, 'Post', 'author_id');
        return $relate;
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        $array = array(
            'id' => 'Id',
            'username' => 'Username',
            'password' => 'Password',
            'salt' => 'Salt',
            'email' => 'Email',
            'profile' => 'Profile',
            'new_pass' => 'New Password',
            'old_pass' => 'Old Password',
            're_new_pass Password' => 'ReNew Password',
        );

        $tArray = array();
        foreach ($array as $key => $val)
            $tArray[$key] = Yii::t('adminuser', $val);

        return $tArray;
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('username', $this->username, true);
        $criteria->compare('password', $this->password, true);
        $criteria->compare('salt', $this->salt, true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('profile', $this->profile, true);
        $criteria->compare('action_string', $this->action_string, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Checks if the given password is correct.
     * @param string the password to be validated
     * @return boolean whether the password is valid
     */
    public function validatePassword($password)
    {
        return $this->hashPassword($password, $this->salt) === $this->password;
    }

    /**
     * Checks if the given password is correct.
     * @param string the password to be validated
     * @return boolean whether the password is valid
     */
    public function checkOldPassword($attribute)
    {
        if ($this->hashPassword($this->{$attribute}, $this->salt) === $this->password)
            return TRUE;
        else
        {
            $this->addError($attribute, Yii::t('adminuser', '{object} is incorrect', array(
                    '{object}' => $this->getAttributeLabel($attribute),
            )));
            return FALSE;
        }
    }

    /**
     * Generates the password hash.
     * @param string password
     * @param string salt
     * @return string hash
     */
    public function hashPassword($password, $salt)
    {
        return md5($salt . $password);
    }

    /**
     * Generates a salt that can be used to generate a password hash.
     * @return string the salt
     */
    protected function generateSalt()
    {
        return uniqid('', true);
    }

    function beforeSave()
    {
        if (parent::beforeSave())
        {
            if ($this->new_pass != '')
            {
                $this->salt = $this->generateSalt();
                $this->password = $this->hashPassword($this->new_pass, $this->salt);
            }
            return TRUE;
        }
        else
            return FALSE;
    }

    public static function passUrl()
    {
        return Yii::app()->controller->createUrl("adminuser/forgotPassword", array(
                'lang' => Yii::app()->language
        ));
    }

    function getObjectName()
    {
        return $this->username;
    }

    static function changePassUrl()
    {
        return Yii::app()->controller->createUrl("adminuser/changePassword", array(
                'lang' => Yii::app()->language
        ));
    }

    static function checkAccess($act, $con)
    {
        $act = ucfirst($act);
        $con = ucfirst($con);

        if (Yii::app()->user->checkAccess("$con.*"))
            return TRUE;

        if (Yii::app()->user->checkAccess("$con.$act"))
            return TRUE;

        return FALSE;
    }

}